package com.hp.bon.sgw.wh.mml.helper;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import com.hp.bon.sgw.wh.mml.common.MsgUtils;

public class LogMsgWriter {
	
	private BufferedWriter logWriter = null;
	private String path = null;
	private long fileSize = 0;
	
	public LogMsgWriter(String path){
		this.path = path;
	}
	
	public void openLogFile(){
		try {
			File file = new File(path);
			if(!file.exists()){
				file.mkdirs();
			}
			file = new File(this.path + MsgUtils.getNowTime() + ".log");
			if(!file.exists()){
				file.createNewFile();
			}
			OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
			logWriter = new BufferedWriter(output);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SecurityException e){
			e.printStackTrace();
		}
	}
	
	public void writeOneLine(String oneLine) {
		if(oneLine==null){
			return;
		}
		if(logWriter==null){
			openLogFile();
		}
		try {
			logWriter.write(oneLine.trim());
			logWriter.write("\r\n");
			logWriter.flush();
			fileSize += oneLine.length();
			//文件超过10M,刚新建立一个日志文件
			if(fileSize >= 5242880){
				fileSize = 0;
				closeLogFile();
				openLogFile();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void closeLogFile(){
		try {
			logWriter.flush();
			logWriter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
